<?php

namespace app\admin\controller;

use brand\Brand;
use brand\build\Columns;
use brand\logic\BrandHelper;
use brand\logic\CurdBuild;
use brand\page\Form;
use brand\page\Table;
use function _error;
use function _success;
use function request;
use function url;

class Curd extends Base
{

    public function _initialize()
    {

        parent::_initialize();
        $addon = $this->request->param('addon');
        if ($addon){
            //插件
            BrandHelper::addonBrandTablesPath($addon);
        }

    }

    public function index()
    {
        return $this->table();
    }

    /**
     * 数据库数据表
     */
    public function table()
    {
        Table::$header_buttons = [];
        $this->curdColumns();

        return parent::index();
    }

    /**
     * 数据库列表
     */
    public function curdColumns()
    {
        CurdBuild::tableColumns();
    }

    /**
     * 字段设置-字段列表
     */
    public function tableFields()
    {


        $db_table = $this->request->param('table');

        if (!$db_table) {
            $this->error('缺少Table');
        }

        $addon = $this->request->param('addon');
        $db_table = BrandHelper::addonTableName($db_table,$addon);

        $tableConfig = BrandHelper::getCurdConfigByName($db_table);
        if (!$tableConfig) return _error('请先生成Curd文件');

        Table::$header_buttons = [];
        Table::$right_buttons = [];
        //顶部按钮
        Table::$custom_button_header[] = Brand::Builder()->build_button('','el-icon-setting')
            ->button_url(url('pageConfig',request()->get())->build())->button_data([])
            ->button_props(Table::buttonProps('页面设置'))
            ->build();



        //CURD设置
        Table::$custom_button[]  = Brand::Builder()->build_button('CURD设置','el-icon-setting')
            ->button_data(['field',request()->get()])
            ->button_url(url('editFieldCurdConf')->build())
            ->button_visible('curd_set')
            ->build();


        //生成CURD
        Table::$custom_button[]  = Brand::Builder()->build_button('自动生成','el-icon-refresh-right','confirm')
            ->button_confirm('若已存在配置，将自动覆盖，自动生成后也可以手动修改')
            ->button_data(['title','field'])
            ->button_url(url('fieldToCurd',request()->get())->build())
            ->build();


        Table::$table_data_url = url('tableFieldsValues',request()->get())->build();


        //设置头信息
        Table::$SurfaceTable->header(Table::header());

        //获取行数据
        $columns =  Table::buildTable( CurdBuild::tableFieldsColumns() );

        //设置行数据
        Table::$SurfaceTable->columns($columns);

        //设置分页
        Table::$SurfaceTable->pagination( Table::pagination());

        //显示页面
        return Table::$SurfaceTable->view();
    }

    /**
     * 字段设置-字段列表 数据
     */
    public function tableFieldsValues()
    {
        $db_table = $this->request->param('table');
        if (!$db_table) {
            $this->error('缺少Table');
        }

        $res = CurdBuild::tableFieldsValues($db_table);

        return _success('',['total'=>count($res),'list'=>$res]);
    }

    /**
     * 表字段生成CURD
     */
    public function fieldToCurd()
    {
        $field = $this->request->param('field');
        $table = $this->request->param('table');
        $title = $this->request->param('title');
        $addon = $this->request->param('addon');
        CurdBuild::fieldToCurd($title,$field,$table,$addon);
        return _success('操作成功');
    }

    /**
     * 获取表数据
     */
    public function _tableData()
    {

        $tableList = CurdBuild::getTableData();
        $addon = $this->request->param('addon');
        if ($addon){
            BrandHelper::addonSetPrefix($addon);
            $tableList = BrandHelper::addonTables($tableList,$addon);
        }

        return _success('',['total' => count($tableList) ,'list' => $tableList]);
    }


    /**
     * 创建文件表单页面
     */
    public function files()
    {
        $table = $this->request->param('table');
        $addon = $this->request->param('addon');

        if (!$table) {
            return _error('缺少Table');
        }

        if ($addon){
            $table = BrandHelper::addonTableName($table,$addon);
        }

        [$columns,$files] = CurdBuild::filesForm($table,$addon);

        //构造Form表单
        $columns_arr = Form::buildForm($columns,$files);


        Form::$SurfaceForm->columns($columns_arr);
        Form::$SurfaceForm->options(
            [
                'async' => [
                    'url' => url('submitMakeFile',request()->get())->build(),
                ],
            ]
        );

        return Form::buildView();
    }


    /**
     * 生成文件操作
     */
    public function submitMakeFile()
    {

        $row_table = $this->request->param('table');
        if (!$row_table) {
            return _error('缺少Table');
        }

        $addon = $this->request->param('addon');
        if ($addon){
            $table = BrandHelper::addonTableName($row_table,$addon);
            BrandHelper::addonSetPrefix($addon);
        }else{
            $table = $row_table;
        }

        $title = $this->request->param('title');
        if (!$title) $title = $table;
        $params = $this->request->param();


        $set_file = $params['set_file'] ?? [];


        try {
            //生成CURD文件
            if (in_array('curd',$set_file)){
                CurdBuild::makeFileCurd($table,$title,$params);
            }

            //设置模型文件
            if (in_array('model',$set_file)){
                CurdBuild::makeFileModel($table,$title,$params,$row_table);
            }
            //生成控制器文件
            if (in_array('controller',$set_file)){
                CurdBuild::makeFileController($table,$title,$params);
            }
            //生成表单验证文件
            if (in_array('validate',$set_file)){
                CurdBuild::makeFileValidate($table,$title,$params,$row_table);
            }

            //生成菜单路由
            if ($params['menu']){
                CurdBuild::makeMenu($table,$title,$params,$addon);
            }

            return  _success('操作成功');
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
        
    }


    /**
     * 同步数据库和curd
     */
    public function syncTableCurd()
    {
        $table = $this->request->param('table');
        if (!$table) $this->error('缺少参数table');
        CurdBuild::syncTableCurd($table);
        $this->success('操作成功');

    }


    /**
     * 编辑CURD表单属性
     */
    public function editFieldCurdConf()
    {
        $table = request()->param('table');
        $field = request()->param('field');
        if (!$field || !$table) $this->error('参数错误');


        [$columns,$raws] = CurdBuild::editFieldCurdForm($table,$field);

        Form::setAsyncUrl( url('submitFieldCurdConf',request()->get())->build() );
        $columns_arr = Form::buildForm($columns,$raws);

        Form::$SurfaceForm->columns($columns_arr);
        return Form::$SurfaceForm->view();

    }

    /**
     * 提交Curd配置
     */
    public function submitFieldCurdConf()
    {
        $table = request()->param('table');
        $field = request()->param('field');
        if (!$field || !$table) $this->error('参数错误');

        CurdBuild::submitFieldCurdConf($field,$table);
        $this->success('操作成功');
    }

    public function pageConfig()
    {
        $table = request()->param('table');
        if (!$table) $this->error('参数错误');

        if ($this->request->isAjax()){
            $post = $this->request->post();
            CurdBuild::setPageConfig($table,$post);
            $this->success('操作成功');
        }


        $columns = CurdBuild::getPageConfigColumns($table);
        $columns_value = CurdBuild::getPageConfigValues($table);
        $columns_arr = Form::buildForm($columns,$columns_value);
        Form::$SurfaceForm->columns($columns_arr);
        Form::setAsyncUrl(url('pageConfig',request()->get())->build() );
        return Form::$SurfaceForm->view();
    }

}